package org.filetransfer.file_transfer_java_backend.controller;
import io.swagger.v3.oas.annotations.Operation;
import org.filetransfer.file_transfer_java_backend.config.RequireAuth;
import org.filetransfer.file_transfer_java_backend.entity.User;
import org.filetransfer.file_transfer_java_backend.model.FileCategoryModel;
import org.filetransfer.file_transfer_java_backend.model.ServiceFileInfoModel;
import org.filetransfer.file_transfer_java_backend.model.ServiceShareInfoModel;
import org.filetransfer.file_transfer_java_backend.service.StatisticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/statistic")
public class StatisticController {
    @Autowired
    public StatisticService statisticService;
    public record ServerStorageInfo(long totalSpace, long usedSpace, long freeSpace) {}
    public record ServerInfo(ServerStorageInfo fileSystem, StatisticService.ServerOverloadInfo overload) {}
    @RequireAuth
    @GetMapping("/server/info")
    @Operation(summary = "获取服务状态信息(资源占用等)")
    public ServerInfo getServerInfo() {
        var free = statisticService.getStorageFreeSpace();
        var used = statisticService.getStorageUsedSpace();
        long total;
        if (free == -1 || used == -1) { //有获取失败
            total = -1;
        } else {
            total = free + used;//计算总空间（用于本程序使用的总空间，不包括操作系统其他文件）
        }
        return new ServerInfo(new ServerStorageInfo(total, used, free), statisticService.getServerOverloadInfo());
    }
    public record ServiceInfo(Optional<ServiceFileInfoModel> fileInfo, Optional<ServiceShareInfoModel> shareInfo) {}
    @GetMapping("/service/statistic")
    @Operation(summary = "获取分享服务统计信息")
    public ServiceInfo getServiceInfo() {
        return new ServiceInfo(
                statisticService.getServiceFileStatistics(null), statisticService.getServiceShareStatistics(null));
    }
    @GetMapping("/file/category")
    @Operation(summary = "获取文件分类信息")
    public List<FileCategoryModel> getFileCategoryInfo() {
        return statisticService.getFileCategoryInfo();
    }
    public record ServiceInfo5Day(ServiceInfo day1, ServiceInfo day2, ServiceInfo day3, ServiceInfo day4,
                                  ServiceInfo day5) {}
    @GetMapping("/service/statistic/5day")
    @Operation(summary = "获取分享服务统计信息(5天)")
    public ServiceInfo5Day getServiceInfo5Day() {
        return new ServiceInfo5Day(
                new ServiceInfo(statisticService.getServiceFileStatistics(0),
                        statisticService.getServiceShareStatistics(0)),
                new ServiceInfo(statisticService.getServiceFileStatistics(1),
                        statisticService.getServiceShareStatistics(1)),
                new ServiceInfo(statisticService.getServiceFileStatistics(2),
                        statisticService.getServiceShareStatistics(2)),
                new ServiceInfo(statisticService.getServiceFileStatistics(3),
                        statisticService.getServiceShareStatistics(3)),
                new ServiceInfo(statisticService.getServiceFileStatistics(4),
                        statisticService.getServiceShareStatistics(5)));
    }
    // @GetMapping("/service/statistic/desktop/dashboard") 
    // Dashboard data structures
    public record StatisticWithChange(long current, double changePercentage) {}
    public record TransferActivityPoint(String time, long uploadCount, long downloadCount) {}
    public record NetworkStatus(boolean connected, String status) {}
    public record StorageUtilization(long usedSpace, long totalSpace, double percentage) {}
    public record DashboardData(
            StatisticWithChange transferredFiles,
            StatisticWithChange totalCapacity,
            StatisticWithChange activeShares,
            NetworkStatus networkStatus,
            StorageUtilization storageUtilization,
            List<TransferActivityPoint> transferActivity,
            List<FileCategoryModel> fileTypeDistribution
    ) {}    @GetMapping("/service/statistic/desktop/dashboard")
    @Operation(summary = "获取桌面仪表板数据")
    public DashboardData getDashboardData() {
        // 获取当前用户ID（如果已登录）
        Long currentUserId = getCurrentUserId();
        
        // 获取当前和上个月的文件统计
        var currentFileStats = (currentUserId != null) ? 
                statisticService.getServiceFileStatisticsByUser(null, currentUserId).orElse(new ServiceFileInfoModel(0L, 0L, 0L, 0L)) :
                statisticService.getServiceFileStatistics(null).orElse(new ServiceFileInfoModel(0L, 0L, 0L, 0L));
                
        var lastMonthFileStats = (currentUserId != null) ?
                statisticService.getServiceFileStatisticsByUser(30, currentUserId).orElse(new ServiceFileInfoModel(0L, 0L, 0L, 0L)) :
                statisticService.getServiceFileStatistics(30).orElse(new ServiceFileInfoModel(0L, 0L, 0L, 0L));
                
        // 计算传输文件变化百分比
        double fileCountChange = calculatePercentageChange(currentFileStats.getFileCount(), lastMonthFileStats.getFileCount());
        double capacityChange = calculatePercentageChange(currentFileStats.getTotalSize(), lastMonthFileStats.getTotalSize());
        
        // 获取当前和上个月的分享统计
        var currentShareStats = (currentUserId != null) ?
                statisticService.getServiceShareStatisticsByUser(null, currentUserId).orElse(new ServiceShareInfoModel(0L)) :
                statisticService.getServiceShareStatistics(null).orElse(new ServiceShareInfoModel(0L));
                
        var lastMonthShareStats = (currentUserId != null) ?
                statisticService.getServiceShareStatisticsByUser(30, currentUserId).orElse(new ServiceShareInfoModel(0L)) :
                statisticService.getServiceShareStatistics(30).orElse(new ServiceShareInfoModel(0L));
                
        double shareCountChange = calculatePercentageChange(currentShareStats.getShareCount(), lastMonthShareStats.getShareCount());
        
        // 获取存储信息
        long usedSpace = statisticService.getStorageUsedSpace();
        long freeSpace = statisticService.getStorageFreeSpace();
        long totalSpace = (usedSpace != -1 && freeSpace != -1) ? usedSpace + freeSpace : -1;
        double storagePercentage = (totalSpace > 0) ? ((double) usedSpace / totalSpace) * 100 : 0;
        
        // 生成传输活动数据 (最近7天的数据)
        List<TransferActivityPoint> transferActivity = generateTransferActivity(currentUserId);
        
        // 获取文件类型分布
        List<FileCategoryModel> fileTypeDistribution = (currentUserId != null) ?
                statisticService.getFileCategoryInfoByUser(currentUserId) :
                statisticService.getFileCategoryInfo();
                
        return new DashboardData(
                new StatisticWithChange(currentFileStats.getFileCount(), fileCountChange),
                new StatisticWithChange(currentFileStats.getTotalSize(), capacityChange),
                new StatisticWithChange(currentShareStats.getShareCount(), shareCountChange),
                new NetworkStatus(true, "连接正常"), // 假设网络正常
                new StorageUtilization(usedSpace, totalSpace, storagePercentage),
                transferActivity,
                fileTypeDistribution
        );
    }    private double calculatePercentageChange(long current, long previous) {
        if (previous == 0) {
            return current > 0 ? 100.0 : 0.0;
        }
        return ((double) (current - previous) / previous) * 100.0;
    }
    
    private List<TransferActivityPoint> generateTransferActivity(Long userId) {
        List<TransferActivityPoint> activity = new java.util.ArrayList<>();
        // 生成最近7天的传输活动数据
        for (int i = 6; i >= 0; i--) {
            var fileStats = (userId != null) ?
                    statisticService.getServiceFileStatisticsByUser(i, userId).orElse(new ServiceFileInfoModel(0L, 0L, 0L, 0L)) :
                    statisticService.getServiceFileStatistics(i).orElse(new ServiceFileInfoModel(0L, 0L, 0L, 0L));
            // 格式化时间 (例如: "12-01", "12-02" 等)
            var date = java.time.LocalDate.now().minusDays(i);
            String timeLabel = String.format("%02d-%02d", date.getMonthValue(), date.getDayOfMonth());
            // 使用文件数量作为上传数据，下载次数作为下载数据
            activity.add(new TransferActivityPoint(
                    timeLabel,
                    fileStats.getFileCount(),
                    fileStats.getTotalDownloadCount()
            ));
        }
        return activity;
    }
    
    /**
     * 获取当前用户ID，如果用户未登录则返回null
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated() 
                && !"anonymousUser".equals(authentication.getPrincipal())
                && authentication.getPrincipal() instanceof User) {
                return ((User) authentication.getPrincipal()).getId();
            }
        } catch (Exception e) {
            // 忽略异常，返回null表示未登录
        }
        return null;
    }
}
